package lk.icta.common.dao.impl;

import lk.icta.common.AppConstants;
import lk.icta.common.ErrorCodes;
import lk.icta.common.dao.InstituteDAO;
import lk.icta.common.dao.PreloadableDAO;
import lk.icta.common.entity.Institute;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Supun Viraj Rathnayaka
 *
 */

public class InstituteDAOImpl extends BaseDAO implements InstituteDAO, PreloadableDAO {

    private final Map<Integer, String> siNames = new HashMap<Integer, String>();
    private final Map<Integer, String> enNames = new HashMap<Integer, String>();
    private final Map<Integer, String> taNames = new HashMap<Integer, String>();

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public void preload() {
        Query query = em.createQuery("SELECT l FROM Institute l");
        List<Institute> results = query.getResultList();
        for (Institute l : results) {
            siNames.put(l.getId(), l.getSiInstituteName());
            enNames.put(l.getId(), l.getEnInstituteName());
            taNames.put(l.getId(), l.getTaInstituteName());
        }
    }


    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public Map<Integer, String> getAllLandUsages(String language, User user) {
        logger.info("Listing Institutes in {}", language);
        Map<Integer, String> result = null;
        if (AppConstants.SINHALA.equals(language)) {
            result = siNames;
        } else if (AppConstants.ENGLISH.equals(language)) {
            result = enNames;
        } else if (AppConstants.TAMIL.equals(language)) {
            result = taNames;
        } else {
            handleException("Unsupported language : " + language, ErrorCodes.INVALID_LANGUAGE);
        }
        if (result != null)
            return result;
        else
            return Collections.emptyMap();
    }
}
